import React, { useContext, useState, useEffect } from "react";
import { Space, Table, Tag, Layout, Button } from "antd";
import { useNavigate } from "react-router-dom";
import type { ColumnsType } from "antd/es/table";
import { ClientContext } from "../App";
import type { InfoType } from "../types/Info";
import { PlusCircleFilled } from "@ant-design/icons";
import { genColorHex } from "../tools/corol";
import { jointMessage } from "../tools/message";

//scene: id => {color,name} mapping
const sceneColorMap = new Map();
const sceneIdMap = new Map();

const Info: React.FC = () => {
  const { client, theme } = useContext(ClientContext);

  const [info, setInfo] = useState([]);

  const navigate = useNavigate();

  // 获取所有场景信息
  useEffect(() => {
    async function getScene() {
      const { message, code, data } = await (
        await client.get("/get/scene")
      ).data;

      if (code == 0) {
        const sceneReg = /(.*)\d/;
        data.scenes.map(({ id, ip, name }: any) => {
          const prefixNameArr = name.match(sceneReg);
          if (prefixNameArr == null) {
            return;
          }
          const prexName = prefixNameArr[1];
          let color = sceneColorMap.get(prexName);
          if (color == undefined) {
            color = genColorHex();
            sceneColorMap.set(prexName, color);
          }
          sceneIdMap.set(id, { color, name });
        });
      }
    }
    getScene();
  }, []);

  // 请求后台的用户信息list
  useEffect(() => {
    async function getInfo() {
      const { message, code, data } = await (
        await client.post("/post/info", { token: client.getToken(), number: 0 })
      ).data;

      if (code == 0) {
        setInfo(data.info);
      } else {
        const { changeMsg } = client.getProps();

        const reason = jointMessage(message, data.reason);
        changeMsg({ msg: reason, code: 1 });
      }
    }
    getInfo();
  }, []);

  const columns: ColumnsType<InfoType> = [
    {
      title: "Key",
      dataIndex: "key",
      key: "key",
    },
    {
      title: "姓名",
      dataIndex: ["detail", "name"],
      key: "name",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "年龄",
      dataIndex: ["detail", "age"],
      key: "age",
    },
    {
      title: "学号/工号",
      dataIndex: ["detail", "ID"],
      key: "ID",
    },
    {
      title: "学院",
      dataIndex: ["detail", "academy"],
      key: "academy",
    },
    {
      title: "性别",
      dataIndex: ["detail", "gender"],
      key: "gender",
    },
    {
      title: "导师",
      dataIndex: ["detail", "supervisor"],
      key: "supervisor",
    },
    {
      title: "允许通过人脸识别的场景",
      key: "privilege",
      dataIndex: "privilege",
      render: (_, { privilege }) => (
        <>
          {privilege.map((p) => {
            const { color = "", name = "" } = sceneIdMap.get(p) ?? {};
            return (
              <Tag color={color} key={p}>
                {name}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={editInfo(record)}>
            Edit
          </Button>
        </Space>
      ),
    },
  ];

  const editInfo = (info: any) => {
    return (e: any) => {
      navigate("insert", { replace: true, state: { info, isEdit: true } });
    };
  };

  // console.log(info);
  return (
    <Layout>
      <div style={{ padding: "20px" }}>
        <Button
          type="primary"
          shape="round"
          icon={<PlusCircleFilled />}
          size="large"
          onClick={(e) => {
            navigate("insert", { replace: true });
          }}
        >
          增加
        </Button>
      </div>
      <Table columns={columns} dataSource={info as InfoType[]} />
    </Layout>
  );
};

export default Info;
